<template>
    <div class="tenant-manage-container">
        <!-- 查询条件区 -->
        <el-form :inline="true" :model="searchForm" class="tenant-filter">
            <el-form-item label="租户标识">
                <el-input v-model="searchForm.tenantId" placeholder="请输入租户标识" clearable />
            </el-form-item>
            <el-form-item label="联系人">
                <el-input v-model="searchForm.contactPerson" placeholder="请输入联系人" clearable />
            </el-form-item>
            <el-form-item label="电话">
                <el-input v-model="searchForm.contactPhone" placeholder="请输入电话" clearable />
            </el-form-item>
            <el-form-item label="租户名称">
                <el-input v-model="searchForm.tenantName" placeholder="请输入租户名称" clearable />
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker v-model="searchForm.registerTime" type="daterange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="fetchTenantList">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 按钮组 -->
        <div class="tenant-actions">
            <el-button type="success" @click="openAddDialog">新增</el-button>
            <el-button type="danger" :disabled="selectedTenants.length === 0"
                @click="confirmBatchDelete">批量删除</el-button>
            <el-button type="warning" :disabled="tenantList.length === 0" @click="exportToExcel">导出Excel</el-button>
        </div>
        <!-- 租户表格 -->
        <el-table :data="tenantList" border stripe style="width: 100%; margin-top: 10px;" v-loading="loading"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="tenantId" label="租户标识" min-width="80" />
            <el-table-column prop="tenantName" label="租户名称" min-width="120" />
            <el-table-column prop="contactPerson" label="联系人" min-width="100" />
            <el-table-column prop="contactPhone" label="电话" min-width="120" />
            <el-table-column prop="adminName" label="管理员" min-width="100" />
            <el-table-column prop="registerTime" label="注册时间" min-width="160" />
            <el-table-column label="操作" min-width="160">
                <template #default="{ row }">
                    <el-button size="small" @click="openEditDialog(row)">修改</el-button>
                    <el-button size="small" type="danger" @click="confirmDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
            :total="pagination.total" @current-change="fetchTenantList" @size-change="fetchTenantList"
            layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50]"
            style="margin-top: 16px; text-align: right;" />
        <!-- 新增/编辑弹窗 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="租户名称" prop="tenantName">
                    <el-input v-model="form.tenantName" />
                </el-form-item>
                <el-form-item label="租户图标" prop="tenantIcon">
                    <el-upload class="avatar-uploader" action="" :show-file-list="false" :before-upload="beforeUpload"
                        :on-change="handleIconChange" :auto-upload="false">
                        <img v-if="form.tenantIconPreview" :src="form.tenantIconPreview" class="avatar"
                            @click="previewIcon" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                    <div v-if="form.tenantIconPreview" class="icon-actions">
                        <el-button icon="el-icon-zoom-in" size="mini"
                            @click="previewIcon">预览&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
                        <el-button icon="el-icon-delete" size="mini"
                            @click="addDeleteIcon">删除&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</el-button>
                    </div>
                    <div style="font-size: 12px; color: #999;  margin-left: 10px; margin-top: 4px;">支持上传 jpg/png/jpeg
                        图片，大小不超过5MB</div>
                </el-form-item>
                <el-form-item label="联系人" prop="contactPerson">
                    <el-input v-model="form.contactPerson" />
                </el-form-item>
                <el-form-item label="电话" prop="contactPhone">
                    <el-input v-model="form.contactPhone" />
                </el-form-item>
                <el-form-item label="管理员" prop="adminName">
                    <el-input v-model="form.adminName" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <div class="editor-container" style="width: 100%;">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef"
                            :defaultConfig="toolbarConfig" :mode="mode" />
                        <Editor style="height: 350px; overflow-y: hidden;" v-model="form.remark"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </div>
            </template>
            <!-- 图标预览弹窗 -->
            <el-dialog v-model="iconPreviewVisible" width="300px" title="图标预览">
                <img :src="form.tenantIconPreview" style="width: 100%;" />
            </el-dialog>
        </el-dialog>
        <!-- 删除确认弹窗 -->
        <el-dialog title="系统提示" v-model="deleteDialogVisible" width="350px">
            <span>是否确认删除该租户？</span>
            <template #footer>
                <el-button @click="deleteDialogVisible = false">取消</el-button>
                <el-button type="danger" @click="deleteTenant">确定</el-button>
            </template>
        </el-dialog>
        <!-- 错误提示弹窗 -->
        <el-dialog title="错误" v-model="errorDialogVisible" width="350px" show-close>
            <span>{{ errorMessage }}</span>
            <template #footer>
                <el-button type="primary" @click="errorDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, shallowRef, nextTick, onMounted } from 'vue';
import TenantService from '../services/TenantService';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import UserService from '../services/UserService';

const tenantList = ref([]);
const selectedTenants = ref([]);
const loading = ref(false);
const pagination = reactive({ page: 1, size: 10, total: 0 });
const searchForm = reactive({
    tenantName: '',
    contactPerson: '',
    contactPhone: '',
    tenantId: '',
    registerTime: []
});

const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = reactive({
    tenantId: undefined,
    tenantName: '',
    tenantIcon: '',
    tenantIconFile: null,
    tenantIconPreview: '',
    contactPerson: '',
    contactPhone: '',
    adminName: '',
    remark: ''
});
const formRef = ref();
const rules = {
    tenantName: [
        { required: true, message: '请输入租户名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    contactPerson: [
        { required: true, message: '请输入联系人', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    contactPhone: [
        { required: true, message: '请输入电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    adminName: [
        { required: true, message: '请输入管理员', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ]
};
const deleteDialogVisible = ref(false);
const deleteRow = ref(null);
const errorDialogVisible = ref(false);
const errorMessage = ref('');
const iconPreviewVisible = ref(false);
const deleteIconFlag = ref(0);
const deleteIconUrl = ref('');

// 富文本相关
const editorRef = shallowRef();
const mode = ref('default');
const toolbarConfig = {};
const editorConfig = { placeholder: '请输入备注...' };
const handleCreated = (editor) => {
    editorRef.value = editor;
};

const imageBaseUrl = 'http://localhost:8088';

// 新增：用于缓存编辑弹窗打开时的原始图片信息
let originalTenantIcon = '';
let originalTenantIconPreview = '';

function showError(msg) {
    errorMessage.value = msg;
    errorDialogVisible.value = true;
}
function resetSearch() {
    searchForm.tenantName = '';
    searchForm.contactPerson = '';
    searchForm.contactPhone = '';
    searchForm.tenantId = '';
    searchForm.registerTime = [];
    pagination.page = 1;
    selectedTenants.value = [];
    fetchTenantList();
}
function openAddDialog() {
    dialogTitle.value = '新增租户';
    Object.assign(form, {
        tenantId: undefined,
        tenantName: '',
        tenantIcon: '',
        tenantIconFile: null,
        tenantIconPreview: '',
        contactPerson: '',
        contactPhone: '',
        adminName: '',
        remark: ''
    });
    dialogVisible.value = true;
    // 重置表单验证状态
    nextTick(() => {
        formRef.value?.clearValidate();
    });
}
async function openEditDialog(row) {
    dialogTitle.value = '修改租户';
    dialogVisible.value = true;
    await nextTick();
    formRef.value?.clearValidate();
    const data = row;
    let iconUrl = data.tenantIcon || '';
    if (iconUrl && !iconUrl.startsWith('http')) {
        iconUrl = imageBaseUrl + iconUrl;
    }
    Object.assign(form, {
        tenantId: data.tenantId,
        tenantName: data.tenantName,
        tenantIcon: data.tenantIcon, // 原始后端字段
        tenantIconFile: null,
        tenantIconPreview: iconUrl, // 用于预览
        contactPerson: data.contactPerson,
        contactPhone: data.contactPhone,
        adminName: data.adminName,
        remark: data.remark || ''
    });
    // 缓存原始图片信息
    originalTenantIcon = data.tenantIcon;
    originalTenantIconPreview = iconUrl;
    deleteIconUrl.value = iconUrl;
    if (editorRef.value) {
        editorRef.value.setHtml(data.remark || '');
    }
}
function confirmDelete(row) {
    deleteRow.value = row;
    deleteDialogVisible.value = true;
}
function handleSelectionChange(selection) {
    selectedTenants.value = selection;
}
async function confirmBatchDelete() {
    if (selectedTenants.value.length === 0) {
        showError('请选择要删除的租户');
        return;
    }
    deleteRow.value = null; // 标记为批量删除
    deleteDialogVisible.value = true;
}
async function deleteTenant() {
    if (deleteRow.value) {
        // 单个删除
        try {
            const res = await TenantService.deleteTenant(deleteRow.value.tenantId);
            if (res.code === 200) {
                deleteDialogVisible.value = false;
                fetchTenantList();
            } else {
                showError(res.message || '删除失败');
            }
        } catch (e) {
            showError(e.message || '删除失败');
        }
    } else if (selectedTenants.value.length > 0) {
        // 批量删除
        try {
            let successCount = 0;
            for (const tenant of selectedTenants.value) {
                const res = await TenantService.deleteTenant(tenant.tenantId);
                if (res.code === 200) successCount++;
            }
            deleteDialogVisible.value = false;
            fetchTenantList();
            if (successCount === selectedTenants.value.length) {
                // 全部成功
            } else {
                showError(`部分删除失败，成功删除${successCount}个租户`);
            }
        } catch (e) {
            showError(e.message || '批量删除失败');
        }
    }
}
function beforeUpload(file) {
    const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isImage) {
        showError('仅支持 jpg/png/jpeg 格式图片');
        return false;
    }
    if (!isLt5M) {
        showError('图片大小不能超过5MB');
        return false;
    }
    return true;
}
function handleIconChange(file) {
    // 只做本地预览，不上传
    if (form.tenantId) {
        deleteIconFlag.value = 1;
    }

    if (!beforeUpload(file.raw)) return;
    form.tenantIconFile = file.raw;

    const reader = new FileReader();
    reader.onload = e => {
        form.tenantIconPreview = e.target.result;
    };
    reader.readAsDataURL(file.raw);

}

function previewIcon() {
    iconPreviewVisible.value = true;
}

function addDeleteIcon() {
    form.tenantIcon = '';
    form.tenantIconFile = null;
    form.tenantIconPreview = '';
    deleteIconFlag.value = 1;
}

async function removeIcon() {
    if (deleteIconUrl.value) {
        const res = await TenantService.deleteTenantIcon(deleteIconUrl.value);
        if (res.code !== 200) {
            showError(res.msg || '图片删除失败');
            return;
        }
    }
    form.tenantIcon = '';
    form.tenantIconPreview = '';
}

function closeDialog() {
    dialogVisible.value = false;
    deleteIconUrl.value = '';
    deleteIconFlag.value = 0;
    // 恢复图片为打开弹窗时的原始状态
    form.tenantIcon = originalTenantIcon;
    form.tenantIconFile = null;
    form.tenantIconPreview = originalTenantIconPreview;
    formRef.value?.resetFields();
}
function submitForm() {
    formRef.value.validate(async (valid) => {
        if (!valid) return;
        try {
            let iconUrl = form.tenantIcon;
            if (form.tenantId) {
                // 修改
                const updateData = {
                    tenantName: form.tenantName,
                    contactPerson: form.contactPerson,
                    contactPhone: form.contactPhone,
                    adminName: form.adminName,
                    remark: form.remark
                };
                if (deleteIconFlag.value === 1) {
                    removeIcon();
                }
                const res = await TenantService.updateTenant(form.tenantId, updateData, form.tenantIconFile);
                console.log(res);
                if (res.code === 200) {
                    dialogVisible.value = false;
                    ElMessage.success({ message: '修改成功' });
                    fetchTenantList();
                } else {
                    showError(res.message || '修改失败');
                }
            } else {
                // 新增
                const addData = {
                    tenantName: form.tenantName,
                    tenantIcon: iconUrl,
                    contactPerson: form.contactPerson,
                    contactPhone: form.contactPhone,
                    adminName: form.adminName,
                    remark: form.remark
                };
                const res = await TenantService.addTenant(form.tenantIconFile, addData);
                console.log(res);
                if (res.code === 200) {
                    dialogVisible.value = false;
                    ElMessage.success({ message: '创建成功' });
                    fetchTenantList();
                } else {
                    showError(res.message || '创建失败');
                }
            }
        } catch (e) {
            showError(e.message || (form.tenantId ? '修改失败' : '创建失败'));
        }
    });
}
async function exportToExcel() {
    try {
        if (tenantList.value.length === 0) {
            showError('没有数据可导出');
            return;
        }
        const XLSX = await import('xlsx');
        const exportData = tenantList.value.map(tenant => ({
            '租户ID': tenant.tenantId,
            '租户名称': tenant.tenantName,
            '联系人': tenant.contactPerson,
            '电话': tenant.contactPhone,
            '管理员': tenant.adminName,
            '注册时间': tenant.registerTime,
            '备注': tenant.remark ? tenant.remark.replace(/<[^>]+>/g, '') : ''
        }));
        const workbook = XLSX.utils.book_new();
        const worksheet = XLSX.utils.json_to_sheet(exportData);
        worksheet['!cols'] = [
            { wch: 10 },
            { wch: 20 },
            { wch: 15 },
            { wch: 15 },
            { wch: 15 },
            { wch: 20 },
            { wch: 30 }
        ];
        XLSX.utils.book_append_sheet(workbook, worksheet, '租户列表');
        const fileName = `租户列表_${new Date().toISOString().split('T')[0]}.xlsx`;
        XLSX.writeFile(workbook, fileName);
    } catch (error) {
        showError('导出失败，请重试');
    }
}
async function fetchTenantList() {
    loading.value = true;
    try {
        const params = {
            page: pagination.page,
            size: pagination.size,
            tenantName: searchForm.tenantName,
            contactPerson: searchForm.contactPerson,
            contactPhone: searchForm.contactPhone,
            tenantId: searchForm.tenantId
        };
        if (searchForm.registerTime && searchForm.registerTime.length === 2) {
            params.startTime = searchForm.registerTime[0];
            params.endTime = searchForm.registerTime[1];
        }
        console.log(params);
        const res = await TenantService.getTenantList(params);
        console.log(res);
        if (res.code === 200) {
            tenantList.value = res.data.list || [];
            pagination.total = res.data.total;
            pagination.page = res.data.page;
            pagination.size = res.data.size;
        } else {
            showError(res.message || '获取租户列表失败');
        }
    } catch (e) {
        showError(e.message || '获取租户列表失败');
    } finally {
        loading.value = false;
    }
}
onMounted(() => {
    fetchTenantList();
    UserService.loadCurrentUser();
});
</script>

<style scoped>
.tenant-manage-container {
    background: #fff;
    min-height: 100vh;
    padding: 24px 32px 0 32px;
}

.tenant-filter {
    margin-bottom: 10px;
}

.tenant-actions {
    margin-bottom: 10px;
    margin-left: 10px;
}

.avatar-uploader {
    display: inline-block;
    width: 80px;
    height: 80px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    margin-right: 10px;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
}

.avatar {
    width: 80px;
    height: 80px;
    display: block;
    border-radius: 6px;
}

.icon-actions * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.icon-actions .el-button {
    padding: 5px 8px;
    line-height: 1;
    font-size: 12px;
    gap: 8px;
}
</style>